﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImgRemakeCore
{
    public class Remake
    {
        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="originalFolder">图片文件路径</param>
        /// <param name="targetFolder">保存文件夹</param>
        /// <param name="quality">压缩质量</param>
        /// <param name="fileSuffix">压缩后的文件名后缀（防止直接覆盖原文件）</param>
        public static void CompressionImage(string originalFolder, string targetFolder, long quality = 100, string fileSuffix = "")
        {
            if (!Directory.Exists(originalFolder))
            {
                throw new FileNotFoundException();
            }
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }

            DirectoryInfo dir = new DirectoryInfo(originalFolder);
            FileInfo[] fileList = dir.GetFiles();
            //DirectoryInfo[] dii = dir.GetDirectories();//如需遍历子文件夹时需要使用
            foreach (FileInfo fileInfo in fileList)
            {
                //var fileInfo = new FileInfo(imagePath);
                var fileName = fileInfo.Name.Replace(fileInfo.Extension, "");
                var targeFileFullName = string.Empty;
                if (string.IsNullOrWhiteSpace(fileSuffix))
                {
                    targeFileFullName = Path.Combine($"{targetFolder}", $"{fileName}{fileInfo.Extension}");
                }
                else
                {
                    targeFileFullName = Path.Combine($"{targetFolder}", $"{fileName}_{fileSuffix}{fileInfo.Extension}");
                }

                //压缩过滤后缀
                var imgType = ImageTypeCheck.CheckImageTypeName(fileInfo.FullName).ToString();
                if (imgType == ImageType.None.ToString())
                {
                    Console.WriteLine("文件格式错误跳过:" + fileInfo.FullName);
                    Console.WriteLine("-------------- next --------------");
                    continue;
                }

                //生成预览
                var targethumbnailFolder = Path.Combine($"{targetFolder}\\Thumbnail");
                var targethumbnailPath = Path.Combine($"{targetFolder}\\Thumbnail", $"{fileName}{fileInfo.Extension}");
                if (!Directory.Exists(targethumbnailFolder))
                {
                    Directory.CreateDirectory(targethumbnailFolder);
                }
                if (imgType == ImageType.GIF.ToString())
                {
                    File.Copy(fileInfo.FullName, targeFileFullName, true);
                    Console.WriteLine("GIF文件压缩跳过:" + fileInfo.FullName);
                    goto MakeThumbnail;
                }

                Console.WriteLine("开始处理源文件:" + fileInfo.FullName);
                var imageByte = CompressionImage(fileInfo.FullName, quality);
                if (imageByte != null)
                {
                    var ms = new MemoryStream(imageByte);
                    var image = Image.FromStream(ms);

                    if (image.Width > 1080)
                    {
                        Resize.MakeThumbnail(fileInfo.FullName, targeFileFullName, 1080, 0, "W");
                    }
                    else
                    {
                        image.Save(targeFileFullName);
                    }
                    Console.WriteLine("质量压缩生成目标文件:" + targeFileFullName);
                    Console.WriteLine($"目标文件信息:Width:{image.Width},Height:{image.Height},Size:{Math.Ceiling(ms.Length / 1024.0)}KB");
                    ms.Close();
                    ms.Dispose();
                    image.Dispose();
                    goto MakeThumbnail;
                }
            MakeThumbnail: Resize.MakeThumbnail(fileInfo.FullName, targethumbnailPath, 400, 400, "CUT");
                Console.WriteLine("-------------- next --------------");
            }
        }

        public static byte[] CompressionImage(string imagePath, long quality)
        {
            using (var fileStream = new FileStream(imagePath, FileMode.Open))
            {
                try
                {
                    var img = Image.FromStream(fileStream);

                    Console.WriteLine($"源文件信息:Width:{img.Width},Height:{img.Height},Size:{Math.Ceiling(fileStream.Length / 1024.0)}KB");
                    using (var bitmap = new Bitmap(img))
                    {
                        var codecInfo = GetEncoder(img.RawFormat);
                        var myEncoder = System.Drawing.Imaging.Encoder.Quality;
                        var myEncoderParameters = new EncoderParameters(1);
                        var myEncoderParameter = new EncoderParameter(myEncoder, quality);
                        myEncoderParameters.Param[0] = myEncoderParameter;
                        using (var ms = new MemoryStream())
                        {
                            bitmap.Save(ms, codecInfo, myEncoderParameters);
                            myEncoderParameters.Dispose();
                            myEncoderParameter.Dispose();
                            return ms.ToArray();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return null;
                }

            }
        }


        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
        }


    }
}
